package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.douwong.student.R;
import com.douwong.student.activity.AnswerRecordActivity;
import com.douwong.student.activity.CaptureActivity;
import com.douwong.student.activity.ClassFileActivity;
import com.douwong.student.activity.ClassRoomTestActivity;
import com.douwong.student.activity.MainActivity;
import com.douwong.student.activity.PrepareActivity;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.BaseFragment;
import com.douwong.student.contant.Config;
import com.douwong.student.enums.E_CommandType;
import com.douwong.student.enums.E_Destination;
import com.douwong.student.factory.ThreadFactory;
import com.douwong.student.model.FileData;
import com.douwong.student.model.TcpPacket;
import com.douwong.student.popuwindow.UpLoadPopuWindow;
import com.douwong.student.socket.LTPServer;
import com.douwong.student.socket.TcpMessageHandle;
import com.douwong.student.utils.FtpUtils;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.utils.UIUtils;

import java.io.File;

import static android.app.Activity.RESULT_OK;



/**
 * @autor yichao
 * @time 2017/3/2215:04
 * @des 课堂
 */
@SuppressLint("ValidFragment")
public class ClassFragment extends BaseFragment implements View.OnClickListener {

    private TextView mTvJoinClass,mTvLeaveClass;
    private static final String TAG = "ClassFragment";
    private RelativeLayout mRlPrepare,mRlClassFile,mrlRecord,mrlClassTest,mrlClassCamera;
    private UpLoadPopuWindow mUpLoadPopuWindow;
    private MainActivity mMainActivity;
    private final int CAMERA_REQUEST_CODE=233;
    private final int FTP_UPLOAD_LOADING = 320;
    private final int FTP_UPLOAD_SUCCESS = 321;
    private final int FTP_UPLOAD_FAIL = 322;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mMainActivity = (MainActivity) activity;
    }

    @Override
    protected View getRootView(LayoutInflater inflater, ViewGroup container) {
        View  contenView=inflater.inflate(R.layout.fgm_mainclass,null);
        mTvJoinClass = (TextView) contenView.findViewById(R.id.class_in_rl);
        mRlPrepare = (RelativeLayout) contenView.findViewById(R.id.prepare_class_ll);
        mRlClassFile = (RelativeLayout) contenView.findViewById(R.id.class_file_rl);
        mTvLeaveClass = (TextView) contenView.findViewById(R.id.class_leave_rl);
        mrlRecord= (RelativeLayout) contenView.findViewById(R.id.record_rl);
        mrlClassTest= (RelativeLayout) contenView.findViewById(R.id.class_Quizzes_rl);
        mrlClassCamera= (RelativeLayout) contenView.findViewById(R.id.class_camera_rl);


        return contenView;
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mTvJoinClass.setOnClickListener(this);
        mRlPrepare.setOnClickListener(this);
        mTvLeaveClass.setOnClickListener(this);
        mRlClassFile.setOnClickListener(this);
        mrlRecord.setOnClickListener(this);
        mrlClassTest.setOnClickListener(this);
        mrlClassCamera.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        getActivity().registerReceiver(mReceiver,mIntentFilter);
        mUpLoadPopuWindow = new UpLoadPopuWindow(getActivity());

    }

    IntentFilter mIntentFilter=new IntentFilter(){
        {
            addAction(Config.LOGIN_CLASS_SUCESS);
            addAction(Config.LOGIN_CLASS_FAILURE);
            addAction(Config.CLOSE_LOGINING_POPUWINDOW);
        }
    };
    BroadcastReceiver mReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Config.LOGIN_CLASS_SUCESS:
                 if (mUpLoadPopuWindow.isShowing()){
                     mUpLoadPopuWindow.dismiss();
                      }
                    mTvJoinClass.setVisibility(View.GONE);
                    mTvLeaveClass.setVisibility(View.VISIBLE);


                    break;

              case Config.LOGIN_CLASS_FAILURE:
                  if (mUpLoadPopuWindow.isShowing()){
                      mUpLoadPopuWindow.dismiss();
                  }
                  mTvJoinClass.setVisibility(View.VISIBLE);
                  mTvLeaveClass.setVisibility(View.GONE);
                    break;
                case Config.CLOSE_LOGINING_POPUWINDOW:
                    if (mUpLoadPopuWindow.isShowing()){
                        mUpLoadPopuWindow.dismiss();
                    }
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.class_in_rl:
                //加入课堂
                if (!BaseApplication.isLogin){
                    ToastUtils.makeText(getActivity(),"请登录");
                    mMainActivity.startLogingActivityForResult();
                    return;

                }
                mUpLoadPopuWindow.startAnimal();
                mUpLoadPopuWindow.showAtLocation(v, Gravity.CENTER,0,0);
                ThreadFactory.getNormalPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        LTPServer.createInstance(getActivity()).startWork();
                    }
                });

                break;
            case R.id.prepare_class_ll:
                if (!BaseApplication.isLogin){
                    ToastUtils.makeText(getActivity(),"请登录");
                    mMainActivity.startLogingActivityForResult();
                    return;

                }

                PrepareActivity.startActivity(getActivity());
                break;
            case R.id.class_leave_rl:
                //退出课堂
                new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage("确定要退出课堂吗？")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                BaseApplication.isCancelConn=true;
                                BaseApplication.isCloseConn=true;
                                TcpMessageHandle.createInstance(mMainActivity).stopCheckHeart();
                                LTPServer.createInstance(getActivity()).endWork();
                                BaseApplication.temTeacherOnline=null;
                                BaseApplication.sTeacherOnline=null;
                                UIUtils.sendBroadcast(getActivity(),Config.LOGIN_CLASS_FAILURE);
                                dialog.dismiss();

                            }
                        }).create().show();


                break;
            case R.id.class_file_rl:
                //课堂文件
                if (!BaseApplication.isLogin){
                    ToastUtils.makeText(getActivity(),"请先登录");
                    mMainActivity.startLogingActivityForResult();
                    return;

                }
                ClassFileActivity.startActivity(getActivity());
                break;

            case R.id.record_rl:
                //课堂记录
                AnswerRecordActivity.startActivity(getActivity());
                break;
            case R.id.class_Quizzes_rl:
                //随堂小考
                if (BaseApplication.sUserBean==null){
                    ToastUtils.makeText(getActivity(),UIUtils.getString(R.string.login_please));
                    mMainActivity.startLogingActivityForResult();
                    return;
                }
                ClassRoomTestActivity.startActivity(getActivity());
                break;
            case R.id.class_camera_rl:
                //拍照上传
                if (!BaseApplication.isLoginClass){
                    ToastUtils.makeText(mMainActivity,"请加入课堂");
                    return;
                }
            //拍照上传
                Intent intentCP=new Intent(mMainActivity, CaptureActivity.class);
                intentCP.putExtra("router", 0);
                startActivityForResult(intentCP,CAMERA_REQUEST_CODE);



                break;
        }
    }
    @Override
    public void handleLongMsg(TcpPacket tcpPacket, E_CommandType commandType) {
        super.handleLongMsg(tcpPacket, commandType);
        LogUtils.i(TAG,tcpPacket.getData().toString());


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mReceiver!=null){
            getActivity().unregisterReceiver(mReceiver);
        }
        if (mUpLoadPopuWindow!=null && mUpLoadPopuWindow.isShowing()){
            mUpLoadPopuWindow.dismiss();
        }
    }
private Handler mHandler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case FTP_UPLOAD_LOADING:
                int currentSize= (int) msg.obj;
           //     mUpLoadPopu.setProgress(currentSize);
                mUpLoadPopuWindow.setProgress(currentSize);
                break;
            case FTP_UPLOAD_SUCCESS:
                mUpLoadPopuWindow.setProgress(100);
                mUpLoadPopuWindow.dismiss();
                mUpLoadPopuWindow.setText("");
                ToastUtils.makeText(mMainActivity,"上传文件成功");
                break;
            case FTP_UPLOAD_FAIL:
                mUpLoadPopuWindow.dismiss();
                ToastUtils.makeText(mMainActivity,"上传文件失败");

                break;
        }

    }
};

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CAMERA_REQUEST_CODE) {
         String picPathSdCar = data.getStringExtra("picPath");
          final       File fileSd=new File(picPathSdCar);


                if (picPathSdCar!=null &&!picPathSdCar.equals("")){

                //    saveFile(data.getStringExtra("picPath"));
                LogUtils.i(TAG,"拍照上传 ："+ data.getStringExtra("picPath"));

                final      String fileDir="/classroom/"+BaseApplication.sUserBean.getSchoolId()+"/student/"
                        +BaseApplication.sUserBean.getPersonalbean().getId()
                        +"/upload/";
                //  /classroom/(学校ID)/student/(学生ID)/upload
                    if (mUpLoadPopuWindow!=null){
                        if (mUpLoadPopuWindow.isShowing()){
                            mUpLoadPopuWindow.dismiss();
                        }

                    }else {
                        mUpLoadPopuWindow=new UpLoadPopuWindow(mMainActivity);
                    }
                    mUpLoadPopuWindow.startAnimal();
                    mUpLoadPopuWindow.showAtLocation(mrlClassCamera, Gravity.CENTER,0,0);
                    ThreadFactory.getDownLoadPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            FtpUtils ftpUtils=new FtpUtils();
                            try {
                                ftpUtils.uploadSingleFile(fileSd, fileDir, new FtpUtils.UploadProgressListener() {
                                    @Override
                                    public void onUploadProgress(String currentStep, long uploadSize, File file) {
                                        switch (currentStep) {
                                            case Config.FTP_UPLOAD_SUCCESS :
                                                Message message = mHandler.obtainMessage();
                                                message.what=FTP_UPLOAD_SUCCESS;
                                                mHandler.sendMessage(message);
                                                //发送上传成功图片
                                                FileData fileData=new FileData(1,fileSd.getName(),fileDir+fileSd.getName(),1,fileSd.length());

                                               LTPServer.createInstance(mMainActivity).sendMsg(fileData, E_CommandType.studentToTeacherFile, E_Destination.teacher,new int[]{BaseApplication.sTeacherOnline.teacher.teacherId});

                                                LogUtils.i(TAG,"图片上传 路径 ： "+fileDir+file.getName());

                                                break;
                                            case Config.FTP_UPLOAD_LOADING :
                                                int prient= (int) ((uploadSize*100/file.length()));
                                                Message message1 = mHandler.obtainMessage();
                                                message1.what=FTP_UPLOAD_LOADING;
                                                message1.obj=prient;
                                                mHandler.sendMessage(message1);
                                                break;
                                            case Config.FTP_CONNECT_FAIL:
                                            case Config.FTP_UPLOAD_FAIL :
                                                Message message2 = mHandler.obtainMessage();
                                                message2.what=FTP_UPLOAD_FAIL;
                                                mHandler.sendMessage(message2);
                                                break;
                                        }



                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                                ToastUtils.makeText(mMainActivity,"上传图片失败");
                                mUpLoadPopuWindow.dismiss();
                            }
                        }
                    });

                }



    }
}}}
